package com.jeeinc.oa.config.filter;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.jeeinc.oa.domain.Account;
import com.jeeinc.oa.utils.AccountUtils;
import com.jeeinc.oa.utils.StringUtils;

public class LogincheckFilter extends BaseFilter {
	private static final String LOGIN_PAGE = "login";
	private static Set<String> unchecked = new HashSet<String>();
	private static String resource = "/resource";

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		unchecked.add("/system/login");
		unchecked.add("/login");
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		HttpSession session = request.getSession();
		Account account = (Account) AccountUtils.getAccount(session);
		String requestUrl = request.getServletPath();
		if (account != null) {
			chain.doFilter(request, response);
		} else if (unchecked.contains(requestUrl)) {
			chain.doFilter(request, response);
		}else if (requestUrl.startsWith(resource)) {
			chain.doFilter(request, response);
		} else {
			if (StringUtils.isBlank(SYSTEM_BASE_PATH)) {
				String path = request.getContextPath();    
				SYSTEM_BASE_PATH = request.getScheme() + "://" + request.getServerName()+":"+request.getServerPort()+path+"/";
			}
			response.sendRedirect(SYSTEM_BASE_PATH + LOGIN_PAGE);
		}
	}
}
